package top.system.dept.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName: Http2Https
 * @Author: Amosen
 * @Since: 2021/5/22
 */

// 强制将http请求转为https请求，原理是开启另一个Connector监听80端口，收到请求后重定向到443端口
    // 现在应该可以进行发票预览，无效连接可能是因为我的https证书和域名不一致，部署一下试试看
@Configuration
public class Http2Https {

    @Value("${server.http-port}")
    private int serverHttpPort;

    @Value("${server.port}")
    private int serverPort;

    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(httpConnector());
        return tomcat;
    }

    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        // Connector监听的http端口
        connector.setPort(serverHttpPort);
        connector.setSecure(false);
        // 监听到http端口后转向的端口
        connector.setRedirectPort(serverPort);
        return connector;
    }

}
